package com.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.entity.Article;
import com.edu.entity.Dict;
import com.edu.mapper.ArticleMapper;
import com.edu.mapper.DictMapper;
import com.edu.service.ArticleService;
import com.edu.service.DictService;
import com.edu.vo.ArticleVo;
import com.edu.vo.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName
 * @Description
 * @Author W.Jian
 * @Date 2021/5/22 13:04
 **/
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private DictService dictService;

    @Autowired
    private DictMapper dictMapper;

    @Override
    public Result listByPage(ArticleVo articleVo) {

        PageHelper.startPage(articleVo.getPageNum() != null ? articleVo.getPageNum() : 1
                , articleVo.getPageSize() != null ? articleVo.getPageSize() : 5);

        List<Article> articleList  =articleMapper.selectListByPage(articleVo.getAuthor()
                ,articleVo.getSchoolId()
                ,articleVo.getType()
                ,articleVo.getTitle()
                ,articleVo.getBody());
        PageInfo<Article> pageInfo = new PageInfo<>(articleList);
        List<Article> list = pageInfo.getList();
        List<ArticleVo> articleVos = new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        list.forEach(x->{
            ArticleVo vo = new ArticleVo();
            BeanUtils.copyProperties(x,vo);
            vo.setAuthorName(x.getRemark());
            vo.setCreateTime(format.format(x.getCreateTime()));
            vo.setUpdateTime(format.format(x.getUpdateTime()));
            articleVos.add(vo);
        });
            return Result.success(articleVos,pageInfo.getTotal());
    }

    @Override
    public Result delete(Long id) {
        Article article = articleMapper.selectById(id);
        if (article == null) {
            return Result.failure("500", "咨询不存在");
        }
        int i = articleMapper.deleteById(id);
        if (i > 0) {
            return Result.success();
        }
        return Result.failure("500", "删除失败");
    }

    @Override
    public Result updateStatus(Long id) {
        Article article = new Article();
        article.setId(id);
        article.setDelFlag(1);
        int i = articleMapper.updateById(article);
        if (i > 0) {
            return Result.success();
        }
        return Result.failure();
    }

    @Override
    public Result listById(Long id) {
        if (id == null) {
            return Result.failure("500", "缺少参数！");
        }
        Article article = articleMapper.selectById(id);
        return Result.success(article, 0);
    }

    @Override
    public Result saveOrUpdateWithDict(Article article) {
        if (article == null) {
            return Result.failure("500", "文章缺失");
        }
        String type = article.getType();
        if (StringUtils.isEmpty(type)) {
            return Result.failure("500", "类型不能为空！");
        }

        //  查询已经存在的标签  获取最大编号
        List<Dict> existDict = (List<Dict>) dictService.listByType("article_type").getData();
        String maxCode = "0";
        List<String> valueList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(existDict)) {
            for (Dict dict : existDict) {
                if (Integer.valueOf(maxCode) < Integer.valueOf(dict.getCode())) {
                    maxCode = dict.getCode();
                }
                valueList.add(dict.getValue());
            }
        }

        //给标签去除空格
        String trim = type.trim();
        //新建标签
        if (!valueList.contains(trim)) {
            List<Dict> dicts = new ArrayList<>();
            Dict dict = new Dict();
            dict.setDelFlag(0);
            dict.setType("article_type");
            dict.setValue(trim);
            String code = String.valueOf(Integer.valueOf(maxCode) + 1);
            dict.setCode(code);
            dicts.add(dict);
            dictService.insertBatch(dicts);

            article.setType(code);
        } else {
            Dict useDict = existDict.stream().filter(dict -> dict.getValue().equals(trim)).collect(Collectors.toList()).get(0);
            article.setType(useDict.getCode());
        }
        if (article.getId() == null) {
            //新增
            articleMapper.insert(article);
        } else {
            //修改
            articleMapper.updateById(article);
        }
        return Result.success();
    }


    @Override
    public List<Map<String, Object>> listByAll(ArticleVo articleVo) {
        /* 按照文章类型查询 */
        List<Map<String, Object>> res = new ArrayList<>();
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", 0);
        List<Article> articles = articleMapper.selectList(queryWrapper);
        Map<String, List<Article>> collect = articles.stream().collect(Collectors.groupingBy(i -> i.getType()));
        collect.forEach((k, v) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("type", dictMapper.queryArticleTypeName(k));
            map.put("data", v);
            res.add(map);
        });

        return res;

    }
}
